package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.VisitorRecords;
import com.ruoyi.business.mapper.VisitorRecordsMapper;
import com.ruoyi.business.param.VisitorCountXmlParam;
import com.ruoyi.business.service.IVisitorRecordsService;
import com.ruoyi.business.vo.VisitDataVO;
import com.ruoyi.business.vo.VisitorCountVo;
import com.ruoyi.business.vo.VisitorCountXmlVo;
import com.ruoyi.business.vo.VisitorRecordsExportVo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 访客记录Service业务层处理
 * 
 * @author qiancheng
 * @date 2025-06-13
 */
@Service
public class VisitorRecordsServiceImpl extends ServiceImpl<VisitorRecordsMapper, VisitorRecords> implements IVisitorRecordsService
{
    @Autowired
    private VisitorRecordsMapper visitorRecordsMapper;

    /**
     * 查询访客记录
     * 
     * @param id 访客记录主键
     * @return 访客记录
     */
    @Override
    public VisitorRecords selectVisitorRecordsById(Long id)
    {
        return visitorRecordsMapper.selectVisitorRecordsById(id);
    }

    /**
     * 查询访客记录列表
     * 
     * @param visitorRecords 访客记录
     * @return 访客记录
     */
    @Override
    public List<VisitorRecords> selectVisitorRecordsList(VisitorRecords visitorRecords)
    {
        return visitorRecordsMapper.selectVisitorRecordsList(visitorRecords);
    }

    /**
     * 新增访客记录
     * 
     * @param visitorRecords 访客记录
     * @return 结果
     */
    @Override
    public int insertVisitorRecords(VisitorRecords visitorRecords)
    {
        // 设置创建时间
        visitorRecords.setCreateTime(DateUtils.getNowDate());
        // 设置默认删除标记：0-正常，1-删除
        if (visitorRecords.getDelFlag() == null || visitorRecords.getDelFlag().trim().isEmpty()) {
            visitorRecords.setDelFlag("0");
        } else {
            // 限制delFlag的值，只允许"0"或"1"
            String delFlag = visitorRecords.getDelFlag().trim();
            if (!"0".equals(delFlag) && !"1".equals(delFlag)) {
                visitorRecords.setDelFlag("0");
            }
        }
        return visitorRecordsMapper.insert(visitorRecords);
    }

    /**
     * 修改访客记录
     * 
     * @param visitorRecords 访客记录
     * @return 结果
     */
    @Override
    public int updateVisitorRecords(VisitorRecords visitorRecords)
    {
        // 设置更新时间
        visitorRecords.setUpdateTime(DateUtils.getNowDate());
        // 验证并修正delFlag的值
        if (visitorRecords.getDelFlag() != null && !visitorRecords.getDelFlag().trim().isEmpty()) {
            String delFlag = visitorRecords.getDelFlag().trim();
            if (!"0".equals(delFlag) && !"1".equals(delFlag)) {
                visitorRecords.setDelFlag("0");
            }
        }
        return visitorRecordsMapper.updateVisitorRecords(visitorRecords);
    }

    /**
     * 批量删除访客记录
     * 
     * @param ids 需要删除的访客记录主键
     * @return 结果
     */
    @Override
    public int deleteVisitorRecordsByIds(Long[] ids)
    {
        return visitorRecordsMapper.deleteVisitorRecordsByIds(ids);
    }

    /**
     * 删除访客记录信息
     * 
     * @param id 访客记录主键
     * @return 结果
     */
    @Override
    public int deleteVisitorRecordsById(Long id)
    {
        return visitorRecordsMapper.deleteVisitorRecordsById(id);
    }

    /**
     * 首页->>访问数据->>获取访客数据统计信息
     * @param visitorRecords
     * @return
     */
    @Override
    public VisitDataVO getVisitStatistics(VisitorRecords visitorRecords) {
        //首页->>访问数据->>获取今日访客数据
        Map<String, Object> todayVisitStats = baseMapper.getTodayVisitStats();
        //首页->>访问数据->>获取昨日访客数据
        Map<String, Object> yesterdayVisitStats = baseMapper.getYesterdayVisitStats();
        
        // 安全获取今日数据，处理空值情况
        BigDecimal todayVisitCount = (BigDecimal) todayVisitStats.get("todayVisitCount");
        BigDecimal lastVisitCount = (BigDecimal) yesterdayVisitStats.get("todayVisitCount");
        Long todayVisitTimes = (Long) todayVisitStats.get("todayVisitTimes");
        
        // 处理空值，设置默认值
        int todayVisitCountValue = (todayVisitCount != null) ? todayVisitCount.intValue() : 0;
        int lastVisitCountValue = (lastVisitCount != null) ? lastVisitCount.intValue() : 0;
        int todayVisitTimesValue = (todayVisitTimes != null) ? todayVisitTimes.intValue() : 0;
        
        //首页->>访问数据->>获取本月访客数据
        Map<String, Object> monthVisitStats = baseMapper.getMonthVisitStats();
        //首页->>访问数据->>获取上月访客数据
        Map<String, Object> lastMonthVisitStats = baseMapper.getLastMonthVisitStats();
        
        BigDecimal monthVisitCount = (BigDecimal) monthVisitStats.get("monthVisitCount");
        BigDecimal lastMonthVisitCount = (BigDecimal) lastMonthVisitStats.get("monthVisitCount");
        Long monthVisitTimes = (Long) monthVisitStats.get("monthVisitTimes");
        
        // 处理空值，设置默认值
        int monthVisitCountValue = (monthVisitCount != null) ? monthVisitCount.intValue() : 0;
        int lastMonthVisitCountValue = (lastMonthVisitCount != null) ? lastMonthVisitCount.intValue() : 0;
        int monthVisitTimesValue = (monthVisitTimes != null) ? monthVisitTimes.intValue() : 0;
        
        //计算较昨日的增长率
        double dayRate = calculateGrowthRate(todayVisitCountValue, lastVisitCountValue);
        //计算较上月的增长率
        double monthRate = calculateGrowthRate(monthVisitCountValue, lastMonthVisitCountValue);
        
        return new VisitDataVO(todayVisitTimesValue,
                               todayVisitCountValue,
                               dayRate,
                               monthVisitTimesValue,
                               monthVisitCountValue,
                               monthRate
        );
    }

    /**
     * 首页->>访问数据->>更多->>根据年月周获取每天访问人数
     * @param VCountXmlParam
     * @return
     */
    @Override
    public VisitorCountVo getCountByDate(VisitorCountXmlParam VCountXmlParam) {
        if (VCountXmlParam.getSelectType()==1) {
            List<VisitorCountXmlVo> countByDateList = baseMapper.getCountByDate(VCountXmlParam);
            if (countByDateList.size()>0) {
                List<String> dayList = countByDateList.stream().map(VisitorCountXmlVo::getOfDay).collect(Collectors.toList());
                List<Integer> countList = countByDateList.stream().map(VisitorCountXmlVo::getDayCount).collect(Collectors.toList());
                return new VisitorCountVo(dayList,countList);
            }
        }
        List<VisitorCountXmlVo> countByWeekList = baseMapper.getCountByWeek(VCountXmlParam);
        if (countByWeekList.size()>0) {
            List<String> dayList = countByWeekList.stream().map(VisitorCountXmlVo::getOfDay).collect(Collectors.toList());
            List<Integer> countList = countByWeekList.stream().map(VisitorCountXmlVo::getDayCount).collect(Collectors.toList());
            return new VisitorCountVo(dayList,countList);
        }
        return null;
    }

    /**
     * 首页->>访问数据->>更多->>根据年月周获取每天访问列表
     * @param VCountXmlParam
     * @return
     */
    @Override
    public List<VisitorRecords> getListByDate(VisitorCountXmlParam VCountXmlParam) {
        if (VCountXmlParam.getSelectType()==1) {
            return baseMapper.selectVisitorRecordsList(new VisitorRecords(VCountXmlParam));
        }
        return baseMapper.selectVisitorListByWeek(VCountXmlParam);
    }

    /**
     * 根据年月周导出访客记录列表
     * @param VCountXmlParam
     */
    @Override
    public List<VisitorRecordsExportVo> getListByDateExport(VisitorCountXmlParam VCountXmlParam) {
        if (VCountXmlParam.getSelectType()==1) {
            return baseMapper.selectVisitorRecordsListExport(new VisitorRecords(VCountXmlParam));
        }
        return baseMapper.selectVisitorListByWeekExport(VCountXmlParam);
    }

    /**
     * 计算较上次增长率
     * @param count
     * @param lastCount
     * @return
     */
    public double calculateGrowthRate(Integer count, Integer lastCount) {
        if (lastCount == 0) {
            return count > 0 ? 100.0 : 0.0;
        }
        return ((count - lastCount) * 1.0 / lastCount) * 100;
    }

}
